package com.tiantianyuegou.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
        import android.support.v4.app.Fragment;
        import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
        import android.widget.ScrollView;
        import android.widget.TextView;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.activity.OneGouGoodsDetail;
import com.tiantianyuegou.adapter.OneGouAdapter;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.model.OneGouModle;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.Tools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

/**
 * 一元购
 * Created by George on 2016/9/2.
 */
public class OneGouFragment extends Fragment implements View.OnClickListener{
    //     http://hjtech.wicp.net:8080/tiantianyuegou-api/one/list?page=1&type=1
    TextView tv_news,tv_hot,tv_end_loding,tv_end,tv_nogoods;
    BaseActivity activity;
    View rootView;
    LoadingDialog dialog;
    String TAG = "OneGouFragment";
    List<OneGouModle> data = new ArrayList<>();
    OneGouAdapter adapter;
    ScrollView scrollView;
    GridView grid_goods;
    PullToRefreshGridView refresh;
    RequestParams params;
    String goodsId;
    private int page = 0;//分页
    private boolean isRefresh = true;
    private boolean isLoadMore = false;
    private String jifen;
    private FrameLayout layout_nogoods;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Tools.changeSystemBar(getActivity());
        getActivity().setTitle("一元购");
        activity = (BaseActivity) getActivity();
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_onegou, container,
                    false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        findViewByIds();
        initListener();
        initData(1+"",1+"");
        return rootView;
    }



    public void findViewByIds() {
        layout_nogoods = (FrameLayout) rootView.findViewById(R.id.layout_nogoods);
        tv_news = (TextView)rootView.findViewById(R.id.tv_news);
        tv_hot = (TextView)rootView.findViewById(R.id.tv_hot);
        tv_end_loding = (TextView)rootView.findViewById(R.id.tv_end_loding);
        tv_end = (TextView)rootView.findViewById(R.id.tv_end);
        grid_goods = (GridView) rootView.findViewById(R.id.grid_goods);
//        tv_nogoods = (TextView) rootView.findViewById(R.id.tv_nogoods);
        refresh = (PullToRefreshGridView) rootView.findViewById(R.id.refresh);
        scrollView = (ScrollView) rootView.findViewById(R.id.pull_refresh_scrollview);
        //下拉刷新
        ILoadingLayout pullDownRefresh = refresh.getLoadingLayoutProxy(true, false);
        pullDownRefresh.setPullLabel("下拉刷新");//下拉提示
        pullDownRefresh.setRefreshingLabel("正在刷新...");//刷新提示
        pullDownRefresh.setReleaseLabel("松开刷新");//下拉一定距离显示的提示
        //上拉加载
        ILoadingLayout pullUpRefresh = refresh.getLoadingLayoutProxy(false, true);
        pullUpRefresh.setPullLabel("上拉加载");
        pullUpRefresh.setRefreshingLabel("正在刷新...");
        pullUpRefresh.setReleaseLabel("松开加载更多");
    }
    public void initListener(){
        layout_nogoods.setVisibility(View.GONE);
        adapter = new OneGouAdapter(activity);
        tv_news.setOnClickListener(this);
        tv_hot.setOnClickListener(this);
        tv_end_loding.setOnClickListener(this);
        tv_end.setOnClickListener(this);
        tv_news.setTextColor(getResources().getColor(R.color.red));
        tv_hot.setTextColor(getResources().getColor(R.color.black));
        tv_end_loding.setTextColor(getResources().getColor(R.color.black));
        tv_end.setTextColor(getResources().getColor(R.color.black));
//        grid_goods.setAdapter(adapter);
        refresh.setAdapter(adapter);
//        设置商品条目的点击事件，当点击条目的时候跳转到相对应的商品详情界面
//        grid_goods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        refresh.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                将商品id进行传递，商品图片，商品名称，抢购时间，已抢购人数，
                Intent intent = new Intent(activity, OneGouGoodsDetail.class);
                intent.putExtra("oneModel",new OneGouModle() );
                intent.putExtra("endTime",data.get(position).getGoodsStart() );//结束倒计时
                intent.putExtra("count",data.get(position).getStats() );//剩余人数
                intent.putExtra("goodsName",data.get(position).getGoodsName());//商品名称
                intent.putExtra("goodsId", data.get(position).getGoodsId());//商品id
                intent.putExtra("goodsMoney", data.get(position).getGoodsMoney());//商品价钱
                intent.putExtra("goodsPhoto", data.get(position).getGoodsPhoto());//商品图片
                intent.putExtra("jifen", jifen);
                startActivity(intent);
            }
        });
        refresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                //下拉刷新
                page = 0;
                initData(1+"",1+"");
                isRefresh = true;
                isLoadMore = false;
                String label = DateUtils.formatDateTime(
                        getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refresh.getLoadingLayoutProxy().setLastUpdatedLabel(label);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                //上拉加载
                initData(page++ +"",1+"");
                isRefresh = false;
                isLoadMore = true;
                String label = DateUtils.formatDateTime(
                        getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refresh.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
//            最新
            case R.id.tv_news:
                //http://hjtech.wicp.net:8080/tiantianyuegou-api/one/list?page=1&type=1
                tv_news.setTextColor(getResources().getColor(R.color.red));
                tv_hot.setTextColor(getResources().getColor(R.color.black));
                tv_end_loding.setTextColor(getResources().getColor(R.color.black));
                tv_end.setTextColor(getResources().getColor(R.color.black));
                initData(1+"",1+"");
                break;
//            最热
            case R.id.tv_hot:
                //     http://hjtech.wicp.net:8080/tiantianyuegou-api/one/list?page=1&type=2
                tv_hot.setTextColor(getResources().getColor(R.color.red));
                tv_news.setTextColor(getResources().getColor(R.color.black));
                tv_end_loding.setTextColor(getResources().getColor(R.color.black));
                tv_end.setTextColor(getResources().getColor(R.color.black));
                initData(1+"",2+"");
                break;
//            即将结束抢购
            case R.id.tv_end_loding:
                //     http://hjtech.wicp.net:8080/tiantianyuegou-api/one/list?page=1&type=3
                tv_end_loding.setTextColor(getResources().getColor(R.color.red));
                tv_news.setTextColor(getResources().getColor(R.color.black));
                tv_hot.setTextColor(getResources().getColor(R.color.black));
                tv_end.setTextColor(getResources().getColor(R.color.black));
                initData(1+"",3+"");
                break;
//            已结束
            case R.id.tv_end:
                // http://hjtech.wicp.net:8080/tiantianyuegou-api/one/list?page=1&type=4
                tv_end.setTextColor(getResources().getColor(R.color.red));
                tv_news.setTextColor(getResources().getColor(R.color.black));
                tv_hot.setTextColor(getResources().getColor(R.color.black));
                tv_end_loding.setTextColor(getResources().getColor(R.color.black));
                initData(1+"",4+"");
                break;

        }
    }
    //   联网进行网络请求数据解析并展示
    private void initData(String page,String type) {
        dialog = new LoadingDialog(activity);
        dialog.showDialog();
        dialog.setMsg("正在加载中");
        params = new RequestParams();
        params.addBodyParameter("page",page);
        params.addBodyParameter("type",type);
        activity.loadData(HttpRequest.HttpMethod.POST, ApiDefine.ONEGOODS, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                dialog.dismiss();
                Log.e(TAG, "请求到的数据是" + responseInfo.result);
//                解析数据并展示
                if (TextUtils.isEmpty(responseInfo.result)){
                    activity.showMsg("获取商品列表失败");
//                    tv_nogoods.setVisibility(View.VISIBLE);

                }else{
                    try {
                        JSONObject object = new JSONObject(responseInfo.result);
                        String code = object.optString("code");
                         jifen = object.getString("ScoreChargePercent");
                        if (code.equalsIgnoreCase("100")){
                            JSONArray array = object.getJSONArray("list");
                            data.clear();
                            for (int i = 0; i <array.length() ; i++) {
                                OneGouModle modle = new OneGouModle();
                                JSONObject obje = array.getJSONObject(i);
                                String goodsName = obje.optString("top_good_name");
                                String goodsStart = obje.optString("top_start_date");
                                String goodsEnd = obje.optString("topEndDate");
                                String goodsPhoto = obje.optString("top_end_date");
                                String goodsMoney = obje.optString("top_money");
                                String stats = obje.optString("top_status");
                                 goodsId = obje.optString("top_id");
                                modle.setGoodsName(goodsName);
                                modle.setGoodsStart(goodsStart);
                                modle.setGoodsEnd(goodsEnd);
                                modle.setGoodsId(goodsId);
                                //http://www.zgttyg.com   图片路径包含gm这个字符串拼接
                                //http://www.zgttyg.com/tiantianyuegou-gm  不包含就拼接
                                if (goodsPhoto.contains("gm")){
                                    http://hjtech.wicp.net:8080/tiantianyuegou-api/upload/project/20160912170452_3.jpg
//                                    http://www.zgttyg.comupload/project/20160912170452_3.jpg
                                    //http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160912170452_3.jpg
                                    modle.setGoodsPhoto("http://www.zgttyg.com"+goodsPhoto);
                                }else {
                                    modle.setGoodsPhoto("http://www.zgttyg.com/tiantianyuegou-gm"+goodsPhoto);
                                }
                                modle.setGoodsPhoto(goodsPhoto);
                                modle.setStats(stats);
                                data.add(modle);
                            }
                            if (data.size()==0){
                                layout_nogoods.setVisibility(View.VISIBLE);
                            }else{
//                            设置适配器显示数据
//                            refresh.setAdapter(adapter);
                            adapter.setData(data);
                            adapter.notifyDataSetChanged();
                            Log.e(TAG, data.size() + "获取到的集合的长度是");
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        if (isRefresh) {
                            isRefresh = false;
                        } else if (isLoadMore) {
                            isLoadMore = false;
//                            page--;
                        }
                    }
                }


            }

            @Override
            public void onFailure(HttpException e, String s) {
                activity.showMsg("当前网络不可用请检查你的网络设置");
                refresh.onRefreshComplete();
                if (isRefresh) {
                    isRefresh = false;
                } else if (isLoadMore) {
                    isLoadMore = false;
//                    page--;
                }

            }
        });

    }

}

